﻿using Nancy;
using Nancy.Bootstrapper;
using Nancy.Extensions;
using Nancy.Responses;
using Nancy.Security;
using System;
using System.Web;

namespace TaskManagementSystem
{
    public class ModuleSecurity
    {
        /// <summary>
        /// Enables forms authentication for the application
        /// </summary>
        /// <param name="pipelines">Pipelines to add handlers to (usually "this")</param>
        public static void Enable(IPipelines pipelines)
        {
            if (pipelines == null)
            {
                throw new ArgumentNullException("pipelines");
            }
            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook());
            pipelines.AfterRequest.AddItemToStartOfPipeline(GetRedirectToLoginHook());
        }

        /// <summary>
        /// Gets the pre request hook for loading the authenticated user's details
        /// from the session.
        /// </summary>
        /// <param name="configuration">Forms authentication configuration to use</param>
        private static Func<NancyContext, Response> GetLoadAuthenticationHook()
        {
            return context =>
            {
                context.CurrentUser = GetUserFromSession(context);

                return null;
            };
        }

        /// <summary>
        /// Gets the post request hook for redirecting to the login page
        /// </summary>
        /// <returns>Post request hook delegate</returns>
        private static Action<NancyContext> GetRedirectToLoginHook()
        {
            return context =>
            {
                if (context.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    if (context.Request.IsAjaxRequest() || context.Request.Method.ToLower() == "post")
                    {
                        var response = new Models.CommandResult(message: "登录超时，请重新登录");
                        context.Response = new TextResponse(Newtonsoft.Json.JsonConvert.SerializeObject(response), "text/plain; charset=utf-8");
                    }
                    else
                    {
                        context.Response = context.GetRedirect("~/Login?returnUrl=" + HttpUtility.UrlEncode(context.Request.Url.ToString()));
                    }
                }
                else if (context.Response.StatusCode == HttpStatusCode.Forbidden)
                {
                    if (context.Request.IsAjaxRequest() || context.Request.Method.ToLower() == "post")
                    {
                        var response = new Models.CommandResult(message: "没权限进行该操作");
                        context.Response = new TextResponse(Newtonsoft.Json.JsonConvert.SerializeObject(response), "text/plain; charset=utf-8");
                    }
                    else
                    {
                        context.Response = new Response
                        {
                            StatusCode = HttpStatusCode.Forbidden,
                            ContentType = "text/html",
                            Contents = stream => ErrorResponse.FromMessagePath(stream, "content/404.html")
                        };
                    }
                }
            };
        }

        public static IUserIdentity GetUserFromSession(NancyContext ctx)
        {
            IUserIdentity identity = new UserIdentity("111", "黄明基", new string[] { "111" });
            //if (ctx.Request.Session != null)
            //{
            //    var localUser = (ctx.Request.Cookies["LoginUser"] as LocalUser);
            //    if (localUser != null)
            //    {
            //        identity = new UserIdentity(localUser.userId, localUser.userName, new string[] { localUser.userRole.ToString() });
            //    }
            //}

            return identity;
        }
    }
}